package com.ysw.exception;

import com.ysw.constant.ICodeStatus;

import java.io.Serializable;

/**
 * @ClassName ServiceException
 * @Description 自定义业务异常类
 * @Author ysw
 * @Date 2022/5/12 17:38
 */
public class ServiceException extends RuntimeException implements Serializable {
    /**
     * 异常信息枚举
     */
    private ICodeStatus codeStatus;

    private static final long serialVersionUID = 787223739740039623L;

    public ServiceException(String code, String message) {
        this.codeStatus = new CodeStatus(code, message);
    }

    public ServiceException(String code) {
        super(code);
    }

    public ServiceException(Throwable cause) {
        super(cause);
    }

    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }

    /**
     * ICodeStatus 构造
     * @param codeStatus
     */
    public ServiceException(ICodeStatus codeStatus) {
        this.codeStatus = codeStatus;
    }

    /**
     * 获取异常内部信息
     *
     * @return
     */
    public ICodeStatus getCodeStatus() {
        return this.codeStatus;
    }

    /**
     * 获取异常信息 ICodeStatus 内部信息
     *
     * @return
     */
    @Override
    public String getMessage() {
        if (this.codeStatus != null) {
            return this.codeStatus.getCode() + " - " + this.codeStatus.getReasonPhrase();
        }
        return super.getMessage();
    }

    /**
     * 用来存储枚举信息
     */
    public final class CodeStatus implements ICodeStatus {
        private String code;
        private String reasonPhrase;

        private CodeStatus(String value, String reasonPhrase) {
            this.code = value;
            this.reasonPhrase = reasonPhrase;
        }

        @Override
        public String getCode() {
            return this.code;
        }

        @Override
        public String getReasonPhrase() {
            return this.reasonPhrase;
        }
    }
}